
Ext.define('FrontSuite.view.ScreenTreePanel', {
    extend       : 'Ext.tree.Panel',  // defines the superclass. results in class inheritance.

    id           : 'screen-tree-panel',
    bodyStyle    : {border:0},
    scroll       : false,
    useArrows    : true,
    rootVisible  : false,
    store        : null,
    contextMenu  : null,

    constructor: function (id) {
        if (id) {
            this.id = id;
        }
        var testMode = FrontSuite.options.test_mode;

        // screen tree store
        this.store = Ext.create('Ext.data.TreeStore', {
            storeId  : 'screen.tree.store',
            autoLoad : true,
            model    : 'ActionTreeModel',
            proxy : {
                type : 'ajax',
                url  : FrontSuite.options.apps_urldir + '/sitefront/front-framework/api.php/service/ext/apptree',
                extraParams: {
                    mode : 'getTree',
                    type : 'screens'
                },
                actionMethods : 'GET'
            },
            root: {
                text     : 'Tree',
                id       : 'src',
                expanded : true
            }
        });

        this.contextMenu = Ext.create('Ext.menu.Menu',{
            items: [
                { id: 'screen-tree-menu-delete', text: 'Delete' },
                { id: 'screen-tree-menu-add',    text: 'Add Folder' }
            ],
            listeners: {
                click: function(menu, item, e, eopts) {
                    if (FrontSuite.session.lastTaskTreeIdClicked) {
                        var taskNodeId, taskParentId, taskLeaf;
                        taskNodeId   = FrontSuite.session.lastTaskTreeIdClicked;
                        taskParentId = FrontSuite.session.lastTaskParentIdClicked;
                        taskLeaf     = FrontSuite.session.lastTaskLeafClicked;
    
                        switch (item.id) {
                            case 'screen-tree-menu-delete':
                                Ext.Ajax.request({
                                    url       : FrontSuite.options.apps_urldir + '/sitefront/front-framework/api.php/service/ext/apptree',
                                    params    : {type : 'screens', op : 'delete', tree_node_id : taskNodeId},
                                    method    : 'GET',
                                    autoAbort : false,
                                    success : function(response){
                                        var selectedNode = Ext.getCmp('screen-tree-panel').getSelectionModel().getSelection()[0];
                                        selectedNode.remove();
                                    },
                                    failure: function(response, opts) {
                                        Ext.MessageBox.show({
                                           title   : 'Status',
                                           msg     : 'server-side failure with status code ' + response.status,
                                           buttons : Ext.MessageBox.OK
                                        });
                                    }
                                });
    
                                break;
                            case 'screen-tree-menu-add':
                                Ext.MessageBox.prompt('Add Folder', 'Please enter folder text:', function(btn, folderVal){
                                    if (btn == 'ok'){
                                        var params = {};
                                        var addedFolderNm = folderVal;
                                        if (taskLeaf) {
                                            params = {type : 'screens', op : 'new', parent_id : taskParentId, previous_sibling_id : taskNodeId, label : addedFolderNm};
                                        }
                                        else {
                                            params = {type : 'screens', op : 'new', drop_position : 'append', parent_id : taskNodeId, label : addedFolderNm};
                                        }
    
                                        Ext.Ajax.request({
                                            url       : FrontSuite.options.apps_urldir + '/sitefront/front-framework/api.php/service/ext/apptree',
                                            params    : params,
                                            autoAbort : false,
                                            success : function(response){
                                                var jsonObj    = Ext.JSON.decode (response.responseText);
                                                var treeNodeId = jsonObj.tree_id;
    
                                                var selectedNode = Ext.getCmp('screen-tree-panel').getSelectionModel().getSelection()[0];
                                                if (selectedNode.data.leaf) {
                                                    selectedNode.parentNode.insertBefore({
                                                        id     : treeNodeId,
                                                        text   : addedFolderNm,
                                                        leaf   : false,
                                                        action : null
                                                    }, selectedNode);
                                                }
                                                else {
                                                    var store = Ext.getCmp('screen-tree-panel').getStore();
                                                    selectedNode.expand();
                                                    if (selectedNode.store.treeStore.tree.nodeHash[treeNodeId] == null && store.isLoading() == false) {
                                                        selectedNode.appendChild({
                                                            id     : treeNodeId,
                                                            text   : addedFolderNm,
                                                            action : null,
                                                            leaf   : false
                                                        });
                                                    }
                                                }
                                            },
                                            failure: function(response, opts) {
                                                Ext.MessageBox.show({
                                                   title   : 'Status',
                                                   msg     : 'server-side failure with status code ' + response.status,
                                                   buttons : Ext.MessageBox.OK
                                                });
                                            }
                                        });
                                    }
                                });
                                break;
                        }

                        FrontSuite.session.lastTaskTreeIdClicked = null;
                    }
                }
            }
        });

        this.superclass.constructor.call(this, id);
        return(this);
    },

    viewConfig : {
        plugins : {
            ptype : 'treeviewdragdrop'
        },
        listeners : {
            drop : function(htmlNodeBelow, data, model, dropPos, obj) {

                var isLoading = this.store.isLoading();

                if (isLoading) {
                    for (var i = 0; i < data.records.length; i++) {

                        var treeNodeId = data.records[i].data.id;
                        var parentId   = model.internalId;

                        //console.log('treeNodeId: ' + treeNodeId + ' ,parentId: ' + parentId  + ' ,dropPos: ' + dropPos);

                        Ext.Ajax.request({
                            url       : FrontSuite.options.apps_urldir + '/sitefront/front-framework/api.php/service/ext/apptree',
                            params    : {type : 'screens', op : 'move', drop_position : dropPos, tree_node_id : treeNodeId, parent_id : parentId},
                            autoAbort : false,
                            success : function(response){
                            },
                            failure: function(response, opts) {
                                Ext.MessageBox.show({
                                   title   : 'Status',
                                   msg     : 'server-side failure with status code ' + response.status,
                                   buttons : Ext.MessageBox.OK
                                });
                            }
                        });
                    }
                }
                else {
                    for (var i = 0; i < data.records.length; i++) {

                        var treeNodeId        = data.records[i].data.id;
                        var parentId          = data.records[i].data.parentId;
                        var nextSiblingId     = data.records[i].nextSibling ? data.records[i].nextSibling.data.id : null;
                        var previousSiblingId = data.records[i].previousSibling ? data.records[i].previousSibling.data.id : null;

                        //console.log('treeNodeId: ' + treeNodeId + ' ,parentId: ' + parentId  + ' ,dropPos: ' + dropPos + ' ,nextSiblingId: ' + nextSiblingId + ' ,previousSiblingId: ' + previousSiblingId);

                        Ext.Ajax.request({
                            url       : FrontSuite.options.apps_urldir + '/sitefront/front-framework/api.php/service/ext/apptree',
                            params    : {type : 'screens', op : 'move', drop_position : dropPos, tree_node_id : treeNodeId, parent_id : parentId, next_sibling_id : nextSiblingId, previous_sibling_id : previousSiblingId},
                            autoAbort : false,
                            success : function(response){
                            },
                            failure: function(response, opts) {
                                Ext.MessageBox.show({
                                   title   : 'Status',
                                   msg     : 'server-side failure with status code ' + response.status,
                                   buttons : Ext.MessageBox.OK
                                });
                            }
                        });
                    }
                }
            }
        }
    },

    listeners : {
        itemclick : function(view, rec, item, index, eventObj) {
            FrontSuite.app.addTab(rec.raw.action);
        },
        itemcontextmenu: function(view, rec, node, index, e) {
            e.stopEvent();
            this.contextMenu.showAt(e.getXY());
            FrontSuite.session.lastTaskTreeIdClicked   = rec.data.id;
            FrontSuite.session.lastTaskParentIdClicked = rec.parentNode.data.id;
            FrontSuite.session.lastTaskLeafClicked     = rec.data.leaf;
            return false;
        }
    },
    //dockedItems: [{
    //    xtype: 'toolbar',
    //    items: [{
    //        text: 'Expand All',
    //        handler: function(){
    //            screenTreePanel.getEl().mask('Expanding tree...');
    //            var toolbar = this.up('toolbar');
    //            toolbar.disable();
    //
    //            screenTreePanel.expandAll(function() {
    //                screenTreePanel.getEl().unmask();
    //                toolbar.enable();
    //            });
    //        }
    //    }, {
    //        text: 'Collapse All',
    //        handler: function(){
    //            var toolbar = this.up('toolbar');
    //            toolbar.disable();
    //
    //            screenTreePanel.collapseAll(function() {
    //                toolbar.enable();
    //            });
    //        }
    //    }]
    //}]

    refresh: function () {
        this.store.reload();
        //FrontSuite.app.message('Status','Refreshing view organizer...');
    }
});

